package com.baibei.ebec.home.zhima;


import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.RaeTabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.home.index.HomeIndexContract;
import com.baibei.ebec.home.shipment.ShipmentFragment;
import com.baibei.ebec.util.ViewUtil;
import com.baibei.model.Area;
import com.baibei.model.BannerInfo;
import com.baibei.model.LastPriceInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.RankingInfo;
import com.baibei.model.ShipmentInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.ui.AppUI;
import com.baibei.widget.CommonRefreshLayout;
import com.blankj.utilcode.utils.ScreenUtils;
import com.bumptech.glide.Glide;
import com.rae.swift.session.SessionManager;
import com.rae.widget.dialog.DialogBuilder;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * 芝麻首页
 * 只能首页下拉刷新
 */
public class ZhiMaIndexFragment extends BasicFragment implements HomeIndexContract.View, OnBannerListener {

    @BindView(R2.id.banner)
    Banner mBanner;
    @BindView(R2.id.tablayout)
    RaeTabLayout mTablayout;
    @BindView(R2.id.view_pager)
    ViewPager mViewPager;
    @BindView(R2.id.refresh_layout)
    CommonRefreshLayout mRefreshLayout;
    @BindView(R2.id.layout_appbarlayout)
    AppBarLayout mAppbarLayout;

    private List<ShipmentFragment> mFragmentList;
    private List<BannerInfo> mBannerInfos;
    Adapter mAdapter;
    private HomeIndexContract.Presenter mPresenter;

    public ZhiMaIndexFragment() {
    }

    public static ZhiMaIndexFragment newInstance() {
        ZhiMaIndexFragment fragment = new ZhiMaIndexFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = inject(HomeIndexContract.Presenter.class);
    }


    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_zhima_index;
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        ViewUtil.setViewHeight(mBanner, (int) (ScreenUtils.getScreenWidth() / 2.0833));

        mFragmentList = new ArrayList<>();

        //fix bug--20170908
        //问题：当上一层使用刷新时，此碎片中的管理器因为tag问题，未能替换掉
        //因此使用此方案，判断管理器中是否有碎片，有则使用原来的，没有则创建
        if (getChildFragmentManager().getFragments() == null || getChildFragmentManager().getFragments().size() == 0) {
            mFragmentList.add(ShipmentFragment.newInstance(Area.XAU.name(), false));
            mFragmentList.add(ShipmentFragment.newInstance(Area.XAG.name(), false));
        } else {
            for (Fragment fragment : getChildFragmentManager().getFragments()) {
                if (fragment instanceof ShipmentFragment) {
                    mFragmentList.add((ShipmentFragment) fragment);
                }
            }
        }

        mTablayout.addTab(mTablayout.newTab().setText("1"));
        mTablayout.addTab(mTablayout.newTab().setText("2"));

        mAdapter = new Adapter(getChildFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        mTablayout.setupWithViewPager(mViewPager);
        mTablayout.removeAllTabs();
        mTablayout.addTab(newTab(R.drawable.ic_europe, "欧洲产区", "Europe"));
        mTablayout.addTab(newTab(R.drawable.ic_uk, "英国产区", "England"));

        mBanner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                Glide.with(context)
                        .load(((BannerInfo) o).getPicUrl())
                        .into(imageView);
            }
        });
        mBanner.setOnBannerListener(this);
        mRefreshLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                mPresenter.start();
                mFragmentList.get(mViewPager.getCurrentItem()).lazyLoad();
            }
        });
        mRefreshLayout.setEnabled(false);
        //是否开启下拉刷新
        mAppbarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0 && !mRefreshLayout.isEnabled()) {
                    mRefreshLayout.setEnabled(true);
                }
                if (verticalOffset < 0 && mRefreshLayout.isEnabled()) {
                    mRefreshLayout.setEnabled(false);
                }

            }
        });
        mViewPager.setOffscreenPageLimit(2);
        mRefreshLayout.disableWhenHorizontalMove(true);
        mPresenter.start();
    }

    private RaeTabLayout.Tab newTab(int bg, String ch, String eng) {
        RaeTabLayout.Tab tab = mTablayout.newTab();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_zhima_tab, null);
        TextView tvBg = view.findViewById(R.id.tv_logo);
        TextView tvCh = view.findViewById(R.id.tv_ch);
        TextView tvEng = view.findViewById(R.id.tv_eng);
        tvBg.setCompoundDrawablesWithIntrinsicBounds(0, bg, 0, 0);
        tvCh.setText(ch);
        tvEng.setText(eng);
        tab.setCustomView(view);
        return tab;
    }

    @Override
    public void onLoadBannerData(List<BannerInfo> data) {
        if (data != null) {
            mBannerInfos = data;
            mBanner.update(data);
        }
    }

    @Override
    public void onLoadClosePrice(List<LastPriceInfo> data) {

    }

    @Override
    public ProductInfo getProduct() {
        return null;
    }

    @Override
    public void onEmptyBanner() {

    }

    @Override
    public void onLoadComplete() {

    }

    @Override
    public void onLoadCloseprice(List<RankingInfo> info) {

    }

    @Override
    public void refreshCompleted() {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.refreshComplete();
        }
    }

    @Override
    public Area getArea() {
        return Area.ALL;
    }


    @Override
    public void onLoadServiceQQFailed(String msg) {
        AppUI.failed(getContext(), msg);
    }

    @Override
    public void hideLoading() {
        AppUI.dismiss();
    }

    @Override
    public void showLoading() {
        AppUI.loading(getContext());
    }


    @Override
    public void onNoMoreData() {

    }

    @Override
    public void onEmptyData(String s) {

    }

    @Override
    public void onLoadData(List<ShipmentInfo> list) {

    }

    @Override
    public void onLoginExpired() {

    }

    @Override
    public void onDestroy() {
        mPresenter.destroy();
        super.onDestroy();
    }

    @Override
    public void OnBannerClick(int i) {
        BannerInfo bannerInfo = mBannerInfos.get(i);
        if (!TextUtils.isEmpty(bannerInfo.getJumpUrl())) {
            AppRouter.routeToWeb(getContext(), bannerInfo.getTitle(), bannerInfo.getJumpUrl());
        }
    }

    /**
     * 碎片适配器
     */
    private class Adapter extends FragmentPagerAdapter {

        Adapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }

    @Override
    public void onLoadBannerFailed(String s) {
        if (getContext() == null) return;
        AppUI.failed(getContext(), s);
    }

    @Override
    public void onLoadServiceQQSuccess(String qq) {
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qq)));
        } catch (Exception e) {
            new DialogBuilder(getContext())
                    .setMessage("启动QQ失败，QQ号码已经复制，请前往QQ添加我们的客服QQ。")
                    .negativeButtonHidden()
                    .show();
        }
    }

    /**
     * 客服
     */
    @OnClick(R2.id.tv_customer_service)
    public void onCustomerClick() {
        //跳转qq
        if (SessionManager.getDefault().isLogin()) {
            if (!isQQClientAvailable(getContext())) {
                new DialogBuilder(getContext()).negativeButtonHidden().setMessage("您的设备还未安装QQ客户端，不能进行临时会话！").show();
                return;
            }
            mPresenter.getServiceQQ();
        } else {
            AppRouter.routeToLogin(getActivity());
        }
    }

    @OnClick(R2.id.tv_recharge)
    public void onRechargeClickListener() {
        //充值
        if (SessionManager.getDefault().isLogin()) {
            AppRouter.routeToRecharge(getContext());
        } else {
            AppRouter.routeToLogin(getActivity());
        }
        //test
        onUmengEvent("充值");
    }


    /**
     * 判断qq是否可用
     */
    public boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }
}
